<template>
  <div class="recycle-page">
    <!-- 推荐活动轮播图 -->
    <el-card class="activity-carousel-card">
      <el-carousel :interval="4000" type="card" height="300px">
        <el-carousel-item v-for="item in recyclingActivities" :key="item.id" @click="openAppointmentDialog(item)">
          <div class="carousel-content">
            <img :src="item.image" alt="活动图片" class="carousel-image" />
            <div class="overlay">
              <h3>{{ item.activityName }}</h3>
              <span class="date">{{ item.time }}</span>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
      <div class="carousel-header">
        <h2>推荐资源回收活动</h2>
      </div>
    </el-card>

    <!-- 资源回收活动列表 -->
    <el-card class="recycle-activities-list">
      <template #header>
        <div class="card-header">
          <span>可预约的回收活动</span>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="8" v-for="activity in recyclingActivities" :key="activity.id">
          <el-card shadow="hover" class="activity-card">
            <img :src="activity.image" class="activity-image" />
            <div class="activity-info">
              <p class="name">活动名称：{{ activity.activityName }}</p>
              <p class="time">时间：{{ activity.time }}</p>
              <p class="location">地点：{{ activity.address }}</p>
              <p class="items">回收物品：{{ activity.items }}</p>
              <el-button type="primary" size="small" @click="openAppointmentDialog(activity)">
                预约活动
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 预约对话框 -->
    <el-dialog
      v-model="appointmentDialogVisible"
      title="预约资源回收活动"
      width="500px"
    >
      <el-form
        ref="appointmentFormRef"
        :model="appointmentForm"
        :rules="appointmentRules"
        label-width="100px"
      >
        <el-form-item label="活动名称">
          <span>{{ selectedActivity.activityName }}</span>
        </el-form-item>
        <el-form-item label="您的姓名" prop="name">
          <el-input v-model="appointmentForm.name" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="appointmentForm.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="appointmentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAppointment">参与活动</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios' 

const appointmentDialogVisible = ref(false)
const selectedActivity = ref(null)
const appointmentFormRef = ref(null)

const appointmentForm = ref({
  name: '',
  phone: '',
  userId:null,
  type:null,
  state:null,
  time:'',
  activityName:''
})

const recyclingActivities = ref([])
const recycle_activities = ref({
    id: null,
    title: '',
    address:'',
    items: '',
    credit:null,
    date: '',
    image:''
})

// 获取当前用户ID
const getCurrentUserId = () => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  return userInfo.id || userInfo.userId
}

onMounted(async () => {
  try {
    const res = await axios.get('http://localhost:9000/resource_recycling/show')
    if (res.data.isOk && Array.isArray(res.data.resource_recycling)) {
      recyclingActivities.value = res.data.resource_recycling
      recommendedActivities.value = res.data.resource_recycling
    } else {
      ElMessage.error('获取活动列表失败')
    }
  } catch (e) {
    ElMessage.error('网络错误，无法获取活动列表')
  }
})


const appointmentRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const openAppointmentDialog = (activity) => {
  selectedActivity.value = activity
  // 重置表单
  Object.assign(appointmentForm.value, {
    username: '',
    phone: '',
  })
  appointmentDialogVisible.value = true
}

const MyActivity = {
      activityId: null,
      mactivityName:'',
      type: null,
      state: null,
      activityTime: '',
      userId: 1,
      address:''
    }

const submitAppointment = async () => {
  try {
   // await appointmentFormRef.value.validate()
    
    // const userId = getCurrentUserId()
    // if (!userId) {
    //   ElMessage.error('请先登录')
    //   return
    // }
    console.log(selectedActivity.value.activityName)
    let fd = new FormData();
    fd.append('mactivityName',selectedActivity.value.activityName);
    fd.append('type',0);
    fd.append('state',0);
    fd.append('activityTime',selectedActivity.value.time)
    fd.append('userId',1);
    fd.append('address',selectedActivity.value.address);
    // 发送预约请求到后端
    const response =  await axios.post('http://localhost:9000/myactivity/insert', fd)
    if (response.data.isOk) {
      ElMessage.success(`成功预约活动：${selectedActivity.value.activityName}，预约人：${appointmentForm.value.name}，电话：${appointmentForm.value.phone}`)
      appointmentDialogVisible.value = false
    } else {
      ElMessage.error(response.data.message || '预约失败')
    }
  } catch (error) {
    ElMessage.error('预约失败，请检查网络连接')
  }
}

const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}

const handleJoin = (activity) => {
  ElMessage.success(`已报名参加：${activity.activity_name}`)
}

</script>

<style scoped>
.recycle-page {
  padding: 20px;
  background-color: #f0f2f5;
}

.activity-carousel-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.carousel-header {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
  color: #fff;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}

.el-carousel__item {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 24px;
  border-radius: 8px;
  overflow: hidden;
}

.carousel-content {
  position: relative;
  width: 100%;
  height: 100%;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0));
  padding: 20px;
  color: #fff;
}

.overlay h3 {
  margin-top: 0;
  margin-bottom: 5px;
}

.overlay p {
  font-size: 14px;
  margin-bottom: 10px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.overlay .date {
  font-size: 12px;
  opacity: 0.8;
}

.recycle-activities-list {
  margin-top: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.activity-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px;
  overflow: hidden;
}

.activity-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.activity-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
}

.activity-info {
  padding: 15px;
  text-align: left;
}

.activity-info h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 18px;
  color: #333;
}

.activity-info p {
  font-size: 14px;
  color: #666;
  margin: 5px 0;
}
</style> 